﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using WuYuHotel.SQLConn;
using WuYuHotel.Tools;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using System.Text;
using WuYuHotel.WX_AccToken;
using System.Xml;

namespace WuYuHotel.Controllers
{
    public class WxRequestController : Controller
    {
        // GET: WxRequest

        //微信商户参数
        //appid=wx8261af4dcdbe9479
        //mch_id=1484638802
        //key=f1d61fbd3047f892457f33691c8f1614
        //secret=94b327f0b2df0a7297ec53cf2adae212


        public ActionResult Index()
        {
            return View();
        }
        public BaseDao dao = new BaseDao();

        public ContentResult ServerToken()
        {
            if (Request.QueryString["signature"] == null ||
                Request.QueryString["timestamp"] == null ||
                Request.QueryString["nonce"] == null ||
                Request.QueryString["echostr"] == null
                )
            {
                return Content("Error,This Request Not From WxServer");
            }
            string signature = Request.QueryString["signature"].ToString();
            string timestamp = Request.QueryString["timestamp"].ToString();
            string nonce = Request.QueryString["nonce"].ToString();
            string echostr = Request.QueryString["echostr"].ToString();

            ArrayList paramList = new ArrayList();
            paramList.Add("Squall001");
            paramList.Add(timestamp);
            paramList.Add(nonce);
            paramList.Sort();

            Dictionary<string, object> datalog = new Dictionary<string, object>();
            datalog.Add("type", int.Parse("2"));
            datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            datalog.Add("OpID", "0");
            datalog.Add("OpLog", "sig=" + signature + "&time=" + timestamp + "&non=" + nonce + "&echostr=" + echostr);
            dao.save("T_LOG", datalog);

            EncryptTool MyEncrypt = new EncryptTool();
            string MySignature = MyEncrypt.SHA1_Hash(paramList[0].ToString() + paramList[1].ToString() + paramList[2].ToString());
            if (signature == MySignature)
            {
                ResultNotify resultNotify = new ResultNotify(Request);
                WxPayData notifyData = resultNotify.GetNotifyData();



                return Content(echostr);
            }
            else
            {
                return Content("This Request Not From Wx");
            }

        }

        //



        /// <summary>
        /// 发起 用户授权方式，获取OpenID
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOpenIDUserInfo()
        {
            string appid = HttpContext.Application["appid"].ToString();
            string secret = HttpContext.Application["secret"].ToString();
            string REDIRECT_URI = HttpUtility.UrlEncode("http://wuyu.cqutlab.cn/WxRequest/CallBack_snsapi_base");

            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
            //snsapi_base方式（静默的方式）
            //string state = "Base";
            //url += "appid=" + appid + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect";

            //snsapi_userinfo方式（需要用户点击授权的方式）
            string state = "userinfo";
            url += "appid=" + appid + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect";


           
            return Redirect(url);
        }


        /// <summary>
        /// 发起 静默方式 获取OpenID
        /// </summary>
        /// <returns></returns>
        public ActionResult GetOpenIDBase()
        {
            string appid = HttpContext.Application["appid"].ToString();
            string secret = HttpContext.Application["secret"].ToString();
            string REDIRECT_URI = HttpUtility.UrlEncode("http://wuyu.cqutlab.cn/WxRequest/CallBack_snsapi_base");

            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
            //snsapi_base方式（静默的方式）
            string state = "Base";
            url += "appid=" + appid + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect";

            //snsapi_userinfo方式（需要用户点击授权的方式）
            //string state = "userinfo";
            //url += "appid=" + appid + "&redirect_uri=" + REDIRECT_URI + "&response_type=codescope=snsapi_userinfo&state=" + state + "#wechat_redirect";

            return Redirect(url);

        }



        public ActionResult CallBack_snsapi_base()
        {
            if (Request.QueryString["code"] == null || Request.QueryString["state"] == null)
            {
                return Content("Error,This Request Not From WxServer");
            }
            string code = Request.QueryString["code"].ToString();
            string state = Request.QueryString["state"].ToString();
            string appid = HttpContext.Application["appid"].ToString();
            string secret = HttpContext.Application["secret"].ToString();

            Dictionary<string, object> datalog = new Dictionary<string, object>();
            datalog.Add("type", int.Parse("10"));
            datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            datalog.Add("OpID", "0");
            datalog.Add("OpLog", "回调函数获取得到code=" + code + "&state=" + state);
            dao.save("T_LOG", datalog);

            string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
            HttpWebRequest req=null;
            HttpWebResponse resp=null;
            StreamReader sr=null;
            string fullhtml = null;
            try
            {
                req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                req.KeepAlive = true;
                req.Timeout = 30000;
                req.ContentType = "application/json;encoding=utf-8";
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应，那么继续等待相应
                {
                    datalog.Clear();
                    datalog.Add("type", int.Parse("2"));
                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    datalog.Add("OpID", "0");
                    datalog.Add("OpLog", "异常，访问第二步是偶，服务器没有返回200，返回值  " + resp.StatusCode.ToString());
                    dao.save("T_LOG", datalog);
                    req.Abort();
                    resp.Close();
                    sr.Close();
                    return Content("微信服务器未响应第二步,查日志");
                }
                sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                fullhtml = sr.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
                ex.StackTrace.ToString();
                datalog.Clear();
                datalog.Add("type", int.Parse("2"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "异常:访问微信服务器第二步抛出的catch :" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);
                req.Abort();
                resp.Close();
                sr.Close();
                return Content("微信服务器未响应第二步,查日志");
            }
            req.Abort();
            resp.Close();
            sr.Close();

            if (fullhtml.Contains("access_token"))
            {

            }
            else
            {
                datalog.Clear();
                datalog.Add("type", int.Parse("2"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "异常：微信第二步返回错误JSON数据包：" + fullhtml.Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);
                return Content("微信服务器未响应第二步,查日志");
            }
            JToken json_AccToken = JToken.Parse(fullhtml);
            string ACCESS_TOKEN = json_AccToken.Value<string>("access_token");
            string REFRESH_TOKEN= json_AccToken.Value<string>("refresh_token");
            string OPENID= json_AccToken.Value<string>("openid");

            //如果是静默方式调用，那么这里就应该返回页面了
            if(state== "Base")
            {
                ViewBag.ACCESS_TOKEN = ACCESS_TOKEN;
                ViewBag.REFRESH_TOKEN = REFRESH_TOKEN;
                ViewBag.OPENID = OPENID;

                Response.Cookies["openid"].Value = OPENID;
                Response.Cookies["openid"].Expires = DateTime.Now.AddMonths(12);
                return View("WxUser_Base");
            }

            //下面是获取用户信息 snsapi_userinfo环节
            url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + ACCESS_TOKEN + "&openid=" + OPENID + "&lang=zh_CN";
            fullhtml = null;
            try
            {
                req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                req.KeepAlive = true;
                req.Timeout = 30000;
                req.ContentType = "application/json;encoding=utf-8";
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应，那么继续等待相应
                {
                    datalog.Clear();
                    datalog.Add("type", int.Parse("2"));
                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    datalog.Add("OpID", "0");
                    datalog.Add("OpLog", "异常，snsapi_userinfo环节时候，服务器没有返回200，返回值  " + resp.StatusCode.ToString());
                    dao.save("T_LOG", datalog);
                    req.Abort();
                    resp.Close();
                    sr.Close();
                    return Content("微信服务器未响应第四步,查日志");
                }
                sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                fullhtml = sr.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
                ex.StackTrace.ToString();
                datalog.Clear();
                datalog.Add("type", int.Parse("2"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "异常，snsapi_userinfo环节时候抛出的catch :" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);
                req.Abort();
                resp.Close();
                sr.Close();
                return Content("第四步GET方式出错,查日志");
                
            }
            req.Abort();
            resp.Close();
            sr.Close();
            if (fullhtml.Contains("openid"))
            {

            }
            else
            {
                datalog.Clear();
                datalog.Add("type", int.Parse("2"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "异常：snsapi_userinfo环节时候，服务器返回值不包含openid，数据可能出错：" + fullhtml.Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);
                return Content("第四步Json数据出错,查日志");

            }
            JToken json_userinfo = JToken.Parse(fullhtml);
            datalog.Clear();
            datalog.Add("type", int.Parse("12"));
            datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            datalog.Add("OpID", "0");
            datalog.Add("OpLog", "最后获取到的JSON数据" + fullhtml.Replace("'", "''").Replace(" ", ""));
            dao.save("T_LOG", datalog);
            OPENID = json_userinfo.Value<string>("openid");
            string NICKNAME = json_userinfo.Value<string>("nickname");
            string SEX = json_userinfo.Value<string>("sex") =="1"?"男":"女";
            string PROVINCE = json_userinfo.Value<string>("province");
            string CITY = json_userinfo.Value<string>("city");
            string COUNTRY = json_userinfo.Value<string>("country");
            string headimgurl = json_userinfo.Value<string>("headimgurl");

            ViewBag.ACCESS_TOKEN = ACCESS_TOKEN;
            ViewBag.REFRESH_TOKEN = REFRESH_TOKEN;
            ViewBag.OPENID = OPENID;
            ViewBag.NICKNAME = NICKNAME;
            ViewBag.SEX = SEX;
            ViewBag.PROVINCE = PROVINCE;
            ViewBag.CITY = CITY;
            ViewBag.COUNTRY = COUNTRY;
            ViewBag.headimgurl = headimgurl;

            Response.Cookies["openid"].Value = OPENID;
            Response.Cookies["openid"].Expires = DateTime.Now.AddMonths(12);
            Response.Cookies["headimgurl"].Value = headimgurl;
            Response.Cookies["headimgurl"].Expires = DateTime.Now.AddMonths(12);

            return View("WxUser_UserInfo");


        }

        /// <summary>
        /// 正式使用的身份认证调用函数
        /// </summary>
        /// <param name="ViewPageName">返回的页面名称，固定返回WxPage控制器</param>
        /// <returns></returns>
        public ActionResult WxRequestGetOpenID(string ViewPageName)
        {
            if(ViewPageName=="" || ViewPageName == null)
            {
                return RedirectToAction("ErrorPage", "WxPage", new { Msg = "设置微信身份认证回调页面错误" });
            }
            string appid = HttpContext.Application["appid"].ToString();
            string secret = HttpContext.Application["secret"].ToString();

            string REDIRECT_URI = HttpUtility.UrlEncode("http://wuyu.cqutlab.cn/WxRequest/WxOpenIdCallBack");
//#if DEBUG
//            string REDIRECT_URI = HttpUtility.UrlEncode("http://15923051435.oicp.net/WxRequest/WxOpenIdCallBack");
//#else
//            string REDIRECT_URI = HttpUtility.UrlEncode("http://wuyu.cqutlab.cn/WxRequest/WxOpenIdCallBack");
//#endif
            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
            string state = ViewPageName;
            //采用静默方式
            //url += "appid=" + appid + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect";
            //采用用户授权方式
            url += "appid=" + appid + "&redirect_uri=" + REDIRECT_URI + "&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect";
            return Redirect(url);
        }

        public ActionResult WxOpenIdCallBack()
        {
            if (Request.QueryString["code"] == null || Request.QueryString["state"] == null)
            {
                return Content("Error,This Request Not From WxServer");
            }
            string code = Request.QueryString["code"].ToString();
            string state = Request.QueryString["state"].ToString();
            string appid = HttpContext.Application["appid"].ToString();
            string secret = HttpContext.Application["secret"].ToString();

            //if (System.Web.HttpContext.Current.Session["code"]== null)
            //{
            //    return null;
            //    System.Web.HttpContext.Current.Session["code"] = code;
            //}
            //else if (code == System.Web.HttpContext.Current.Session["code"].ToString())
            //{
            //    return new EmptyResult();
            //}
            //else
            //{
            //    System.Web.HttpContext.Current.Session["code"] = code;
            //}
            

            Dictionary<string, object> datalog = new Dictionary<string, object>();
            datalog.Add("type", int.Parse("10"));
            datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            datalog.Add("OpID", "0");
            datalog.Add("OpLog", "回调函数获取得到code=" + code + "&state=" + state);
            dao.save("T_LOG", datalog);

            string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
            HttpWebRequest req = null;
            HttpWebResponse resp = null;
            StreamReader sr = null;
            string fullhtml = null;
            try
            {
                req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                req.KeepAlive = true;
                req.Timeout = 30000;
                req.ContentType = "application/json;encoding=utf-8";
                System.Diagnostics.Debug.WriteLine("code换token，本次来的SessionId=" + Session.SessionID+"time="+DateTime.Now.ToString());
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应，那么继续等待相应
                {
                    datalog.Clear();
                    datalog.Add("type", int.Parse("2"));
                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    datalog.Add("OpID", "0");
                    datalog.Add("OpLog", "异常，访问第二步是偶，服务器没有返回200，返回值  " + resp.StatusCode.ToString());
                    dao.save("T_LOG", datalog);
                    req.Abort();
                    resp.Close();
                    sr.Close();
                    return Content("微信服务器未响应第二步,查日志");
                }
                sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                fullhtml = sr.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
                ex.StackTrace.ToString();
                datalog.Clear();
                datalog.Add("type", int.Parse("2"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "异常:访问微信服务器第二步抛出的catch :" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);
                req.Abort();
                resp.Close();
                sr.Close();
                return Content("微信服务器未响应第二步,查日志");
            }
            req.Abort();
            resp.Close();
            sr.Close();

            if (fullhtml.Contains("access_token"))
            {

            }
            else
            {
                datalog.Clear();
                datalog.Add("type", int.Parse("2"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "异常：微信第二步返回错误JSON数据包：" + fullhtml.Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);

                //ViewBag.Url = "/WxPage/" + state;
                //return View("RedirectView");
                //return Content("微信服务器未响应第二步,查日志");
                return RedirectToAction(state, "WxPage");
                //return null;

            }
            JToken json_AccToken = JToken.Parse(fullhtml);
            string ACCESS_TOKEN = json_AccToken.Value<string>("access_token");
            string REFRESH_TOKEN = json_AccToken.Value<string>("refresh_token");
            string OPENID = json_AccToken.Value<string>("openid");


            //ViewBag.ACCESS_TOKEN = ACCESS_TOKEN;
            //ViewBag.REFRESH_TOKEN = REFRESH_TOKEN;
            //ViewBag.OPENID = OPENID;



            //下面是获取用户信息 snsapi_userinfo环节
            url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + ACCESS_TOKEN + "&openid=" + OPENID + "&lang=zh_CN";
            fullhtml = null;
            try
            {
                req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                req.KeepAlive = true;
                req.Timeout = 30000;
                req.ContentType = "application/json;encoding=utf-8";
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应，那么继续等待相应
                {
                    datalog.Clear();
                    datalog.Add("type", int.Parse("2"));
                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    datalog.Add("OpID", "0");
                    datalog.Add("OpLog", "异常，snsapi_userinfo环节时候，服务器没有返回200，返回值  " + resp.StatusCode.ToString());
                    dao.save("T_LOG", datalog);
                    req.Abort();
                    resp.Close();
                    sr.Close();
                    return Content("微信服务器未响应第四步,查日志");
                }
                sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                fullhtml = sr.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
                ex.StackTrace.ToString();
                datalog.Clear();
                datalog.Add("type", int.Parse("2"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "异常，snsapi_userinfo环节时候抛出的catch :" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);
                req.Abort();
                resp.Close();
                sr.Close();
                return Content("第四步GET方式出错,查日志");

            }
            req.Abort();
            resp.Close();
            sr.Close();
            if (fullhtml.Contains("openid"))
            {

            }
            else
            {
                datalog.Clear();
                datalog.Add("type", int.Parse("2"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "异常：snsapi_userinfo环节时候，服务器返回值不包含openid，数据可能出错：" + fullhtml.Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);
                return Content("第四步Json数据出错,查日志");

            }
            JToken json_userinfo = JToken.Parse(fullhtml);
            datalog.Clear();
            datalog.Add("type", int.Parse("12"));
            datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            datalog.Add("OpID", "0");
            datalog.Add("OpLog", "最后获取到的JSON数据" + fullhtml.Replace("'", "''").Replace(" ", ""));
            dao.save("T_LOG", datalog);
            OPENID = json_userinfo.Value<string>("openid");
            string NICKNAME = json_userinfo.Value<string>("nickname");
            string SEX = json_userinfo.Value<string>("sex") == "1" ? "男" : "女";
            string PROVINCE = json_userinfo.Value<string>("province");
            string CITY = json_userinfo.Value<string>("city");
            string COUNTRY = json_userinfo.Value<string>("country");
            string headimgurl = json_userinfo.Value<string>("headimgurl");

            ViewBag.ACCESS_TOKEN = ACCESS_TOKEN;
            ViewBag.REFRESH_TOKEN = REFRESH_TOKEN;
            ViewBag.OPENID = OPENID;
            ViewBag.NICKNAME = NICKNAME;
            ViewBag.SEX = SEX;
            ViewBag.PROVINCE = PROVINCE;
            ViewBag.CITY = CITY;
            ViewBag.COUNTRY = COUNTRY;
            ViewBag.headimgurl = headimgurl;

            //System.Web.HttpContext.Current.Response.Cookies["openid"].Value = OPENID;
            //System.Web.HttpContext.Current.Response.Cookies["openid"].Expires = DateTime.Now.AddMonths(12);
            //System.Web.HttpContext.Current.Response.Cookies["headimgurl"].Value = headimgurl;
            //System.Web.HttpContext.Current.Response.Cookies["headimgurl"].Expires = DateTime.Now.AddMonths(12);
            //System.Web.HttpContext.Current.Response.Cookies["nickname"].Value = NICKNAME;
            //System.Web.HttpContext.Current.Response.Cookies["nickname"].Expires = DateTime.Now.AddMonths(12);


            //System.Web.HttpContext.Current.Request.Cookies["openid"].Value = OPENID;
            //System.Web.HttpContext.Current.Request.Cookies["openid"].Expires = DateTime.Now.AddMonths(12);
            //System.Web.HttpContext.Current.Request.Cookies["headimgurl"].Value = headimgurl;
            //System.Web.HttpContext.Current.Request.Cookies["headimgurl"].Expires = DateTime.Now.AddMonths(12);
            //System.Web.HttpContext.Current.Request.Cookies["nickname"].Value = NICKNAME;
            //System.Web.HttpContext.Current.Request.Cookies["nickname"].Expires = DateTime.Now.AddMonths(12);


            //http://www.cnblogs.com/shenyixin/p/3610914.html
            //http://www.cnblogs.com/zsxfbj/p/safari_cookie_not_write.html
            if (Response.Cookies["openid"] == null)
            {
                Response.Cookies.Add(new HttpCookie("openid", OPENID));
            }
            else
            {
                Response.Cookies["openid"].Value = OPENID;
            }

            if (Response.Cookies["headimgurl"] == null)
            {
                Response.Cookies.Add(new HttpCookie("headimgurl", headimgurl));
            }
            else
            {
                Response.Cookies["headimgurl"].Value = headimgurl;
            }

            if (Response.Cookies["nickname"] == null)
            {
                Response.Cookies.Add(new HttpCookie("nickname", HttpUtility.UrlEncode(NICKNAME,Encoding.UTF8)));
            }
            else
            {
                Response.Cookies["nickname"].Value = HttpUtility.UrlEncode(NICKNAME, Encoding.UTF8);
            }

            //ViewBag.Url = "/WxPage/" + state;
            //return View("RedirectView");
            return RedirectToAction(state, "WxPage");


            //return View("WxUser_UserInfo");


        }

        public ActionResult AddMyCookies()
        {
            Response.Cookies["openid"].Value = "ootlZwda9ehK2ypgSbrR7PTF6vug";
            Response.Cookies["openid"].Expires = DateTime.Now.AddMonths(12);
            Response.Cookies["headimgurl"].Value = "http://wx.qlogo.cn/mmhead/0wRpPfN90ibB9ibQUNviaE8S1fJ6OibSuBX0bxorZt6XR9FiaBXyKDTic3Qw/0";
            Response.Cookies["headimgurl"].Expires = DateTime.Now.AddMonths(12);
            Response.Cookies["nickname"].Value = HttpUtility.UrlEncode("强强", Encoding.UTF8);
            Response.Cookies["nickname"].Expires = DateTime.Now.AddMonths(12);

            return RedirectToAction("Index", "WxPage");

        }

        public ActionResult ClearCookies()
        {
            if (Request.Cookies["openid"] != null)
            {
                Response.Cookies["openid"].Value = Request.Cookies["openid"].ToString();
                Response.Cookies["openid"].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["headimgurl"].Value = Request.Cookies["headimgurl"].ToString();
                Response.Cookies["headimgurl"].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["nickname"].Expires = DateTime.Now.AddDays(-1);
            }
            return RedirectToAction("TestView1", "Test");

        }

        public Dictionary<string,object> wxPageConfig(string pageUrl)
        {
            string absoluteURL = pageUrl;
            string appid = System.Web.HttpContext.Current.Application["appId"].ToString();
            string jsapi_ticket = System.Web.HttpContext.Current.Application["jsapi_ticket"].ToString();
            string noncestr = System.Web.HttpContext.Current.Application["noncestr"].ToString();
            string UNIXTime = System.Web.HttpContext.Current.Application["UNIXTime"].ToString();
            EncryptTool Encrypt = new EncryptTool();
            string signature = Encrypt.SHA1_Hash("jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + UNIXTime + "&url=" + absoluteURL);

            Dictionary<string, object> map = new Dictionary<string, object>();
            map.Add("appId", appid);
            map.Add("jsapi_ticket", jsapi_ticket);
            map.Add("noncestr", noncestr);
            map.Add("UNIXTime", UNIXTime);
            map.Add("signature", signature);
            return map;
        }

        public ActionResult TestPayView()
        {


            if (CheckCookies())
            {
                return View("testPay");
            }
            else
            {
                //throw new WxPayException("测试的exception东西");

                //这里表示如果没有的话，就该去引导用户访问微信身份授权页面
                System.Web.HttpContext.Current.Session["code"] = "null";
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Index" });
            }
        }
        /// <summary>
        /// 前台发起支付申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult TestPay()
        {
            if (CheckCookies())
            {
                JsApiPay jsApiPay = new JsApiPay();
                jsApiPay.openid = Request.Cookies["openid"].Value;
                jsApiPay.total_fee = 1;
                try
                {
                    WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();
                    string wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数   

                    var result = new { err = "ok", Param = wxJsApiParam };
                    return Json(result);

                }
                catch (Exception ex)
                {
                    return RedirectToAction("ErrorPage", "WxPage", new { Msg = "查询订单有误" });
                    //throw;
                }


                return Json(new { err = "errror" });
            }
            else
            {
                //throw new WxPayException("微信前台ajax的时候，cookies获取失败");
                //这里表示如果没有的话，就该去引导用户访问微信身份授权页面
                System.Web.HttpContext.Current.Session["code"] = "null";
                //return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Index" });
                return Json(new { err = "errror" });
            }

            
        }


        public ActionResult WxPayNotifyCallBack()
        {          
            ResultNotify resultNotify = new ResultNotify(Request);
            //这里做相应的操作
            try
            {
                //直接处理回调消息
                WxPayData DataResult = resultNotify.MyProcessNotify();
                string appid = DataResult.GetValue("appid").ToString();
                string attach = DataResult.GetValue("attach").ToString();
                string bank_type = DataResult.GetValue("bank_type").ToString();
                string fee_type = DataResult.GetValue("fee_type").ToString();
                string is_subscribe = DataResult.GetValue("is_subscribe").ToString();
                string mch_id = DataResult.GetValue("mch_id").ToString();
                string nonce_str = DataResult.GetValue("nonce_str").ToString();
                string openid = DataResult.GetValue("openid").ToString();
                //这个是查询条件
                string out_trade_no = DataResult.GetValue("out_trade_no").ToString();
                /////////////////////
                string result_code = DataResult.GetValue("result_code").ToString();
                string return_code = DataResult.GetValue("return_code").ToString();
                string sign = DataResult.GetValue("sign").ToString();
                string time_end = DataResult.GetValue("time_end").ToString();
                string total_fee = DataResult.GetValue("total_fee").ToString();
                string trade_type = DataResult.GetValue("trade_type").ToString();
                string transaction_id = DataResult.GetValue("transaction_id").ToString();

                Dictionary<string, object> DataResultMap = new Dictionary<string, object>
                {
                    ["appid"] = appid,
                    ["attach"] = attach,
                    ["bank_type"] = bank_type,
                    ["fee_type"] = fee_type,
                    ["is_subscribe"] = is_subscribe,
                    ["mch_id"] = mch_id,
                    ["nonce_str"] = nonce_str,
                    ["openid"] = openid,
                    ["result_code"] = result_code,
                    ["return_code"] = return_code,
                    ["sign"] = sign,
                    ["time_end"] = time_end,
                    ["total_fee"] = total_fee,
                    ["trade_type"] = trade_type,
                    ["transaction_id"] = transaction_id
                };
                if(1!=dao.update("t_o_WxCallBack", DataResultMap, "out_trade_no='" + out_trade_no + "'"))
                {
                    return Content("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[out_trade_no=error]]></return_msg></xml>");
                    //throw new WxPayException("更新WxCallBack表错误");
                    //return new EmptyResult();
                }
                List<Dictionary<string, object>> PrePayList = new List<Dictionary<string, object>>();
                string sql = "select State,ZZOrderId from t_o_WxPrePay where WxTradeNo='" + out_trade_no + "'";
                PrePayList = dao.GetList(sql, new string[] { "State", "ZZOrderId" });
                if (PrePayList[0]["State"].ToString().Equals("0"))
                {
                    sql = "update t_o_WxPrePay set State=1 where WxTradeNo='" + out_trade_no + "'";
                    BaseDao.execute(sql);

                    //发短信
                    sql = "SELECT a.HotelId,b.hotelName,b.roomTypeName,a.Tel,a.RoomNum,CONVERT(VARCHAR(10),a.EnterTime,120) as etime,";
                    sql += " CONVERT(VARCHAR(10),a.LeaveTime,120) as ltime FROM t_o_order a INNER JOIN t_m_room b ON a.HotelId=b.hotelId AND a.RoomTypeId=b.roomTypeId";
                    sql += " where ZZOrderId='" + PrePayList[0]["ZZOrderId"].ToString() + "'";
                    List<Dictionary<string, object>> SMSList = new List<Dictionary<string, object>>();
                    SMSList = dao.GetList(sql, new string[] { "HotelId", "hotelName", "roomTypeName", "Tel", "RoomNum", "etime", "ltime" });
                    


                    //调用住哲的订单付款
                    XmlDocument xml = new XmlDocument();
                    ZhuZheAPI ZZAPI = new ZhuZheAPI();
                    xml = ZZAPI.FuncAction("zhuzher.order.payOrderInfo", ZZAPI.PayOrder(SMSList[0]["HotelId"].ToString(), PrePayList[0]["ZZOrderId"].ToString(), out_trade_no, (int.Parse(total_fee) / 100).ToString()));
                    if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("调用成功"))
                    {
                        //把本地订单表设置为已付款
                        sql = "update t_o_order set State=1 where ZZOrderId='" + PrePayList[0]["ZZOrderId"].ToString() + "'";
                        BaseDao.execute(sql);

                        BaseDao basedao = new BaseDao();
                        Dictionary<string, object> datalog = new Dictionary<string, object>();
                        datalog.Add("type", int.Parse("0"));
                        datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        datalog.Add("OpID", "0");
                        datalog.Add("OpLog", "API发起付款申请成功：" + xml.OuterXml.Replace("'", "''").Replace(" ", ""));
                        basedao.save("T_LOG", datalog);

                        //调用成功了再发短信
                        SMS.SMS_PayOver(SMSList[0]["RoomNum"].ToString(), "吴隅·" + SMSList[0]["hotelName"].ToString() + "·" + SMSList[0]["roomTypeName"].ToString(), SMSList[0]["etime"].ToString(), SMSList[0]["ltime"].ToString(), SMSList[0]["Tel"].ToString());

                    }
                    else
                    {
                        BaseDao basedao = new BaseDao();
                        Dictionary<string, object> datalog = new Dictionary<string, object>();
                        datalog.Add("type", int.Parse("0"));
                        datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        datalog.Add("OpID", "0");
                        datalog.Add("OpLog", "API发起付款申请有误：" + xml.OuterXml.Replace("'", "''").Replace(" ", ""));
                        basedao.save("T_LOG", datalog);
                        //return RedirectToAction("ErrorPage", "WxPage", new { Msg = "查询订单有误" });
                        
                    }

                }

                //

                return Content("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");



            }
            catch (Exception ex)
            {
                //若签名错误，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);

                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("0"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "WxCallBack" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                dao.save("T_LOG", datalog);
                //throw new WxPayException("WxCallBack Code Fail!!!"+ ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                //System.Diagnostics.Debug.WriteLine("Sign check error : " + res.ToXml());
                //return RedirectToAction("ErrorPage", "WxPage", new { Msg = "前面错误" });
                //throw;
            }
            return new EmptyResult();


        }



        private bool CheckCookies()
        {

            if (
                    System.Web.HttpContext.Current.Request.Cookies["openid"] != null && System.Web.HttpContext.Current.Request.Cookies["headimgurl"] != null && System.Web.HttpContext.Current.Request.Cookies["nickname"] != null
                )
                if (System.Web.HttpContext.Current.Request.Cookies["openid"].Value != "" && System.Web.HttpContext.Current.Request.Cookies["headimgurl"].Value != "" && System.Web.HttpContext.Current.Request.Cookies["nickname"].Value != "")
                {
                    Response.Cookies["openid"].Value = Request.Cookies["openid"].Value;
                    Response.Cookies["openid"].Expires = DateTime.Now.AddMonths(12);
                    Response.Cookies["headimgurl"].Value = Request.Cookies["headimgurl"].Value;
                    Response.Cookies["headimgurl"].Expires = DateTime.Now.AddMonths(12);
                    Response.Cookies["nickname"].Value = Request.Cookies["nickname"].Value;
                    Response.Cookies["nickname"].Expires = DateTime.Now.AddMonths(12);
                    System.Diagnostics.Debug.WriteLine("检测到cookies正确，openid=" + Request.Cookies["openid"].Value + "nickname=" + Response.Cookies["nickname"].Value);
                    return true;
                }
            System.Diagnostics.Debug.WriteLine("检测到cookies不对," + Request.Cookies.Count.ToString());
            return false;
        }

        public ActionResult setCookie()
        {
            Response.Cookies["openid"].Value = "om4f9v6MwQ70dujvUPfaR46MJ7qE";
            Response.Cookies["openid"].Expires = DateTime.Now.AddMonths(12);
            Response.Cookies["headimgurl"].Value = "http://wx.qlogo.cn/mmhead/0wRpPfN90ibB9ibQUNviaE8S1fJ6OibSuBX0bxorZt6XR9FiaBXyKDTic3Qw/0";
            Response.Cookies["headimgurl"].Expires = DateTime.Now.AddMonths(12);
            Response.Cookies["nickname"].Value =  "squall";
            Response.Cookies["nickname"].Expires = DateTime.Now.AddMonths(12);
            return RedirectToAction("MainView", "WxPage");
        }



        public ActionResult WxCard()
        {
            ViewBag.ACCESS_TOKEN = System.Web.HttpContext.Current.Application["acc_Token"].ToString();

            

            Dictionary<string, object> base_info = new Dictionary<string, object>()
            {
                ["logo_url"] = "http://wuyu.cqutlab.cn/Content/IMG/logocard.jpg",
                ["brand_name"] = "无隅",
                ["code_type"] = "CODE_TYPE_TEXT",
                ["title"] = "无隅酒店会员卡",
                ["color"] = "Color010",
                ["notice"] = "使用时向服务员出示此券",
                ["service_phone"] = "020-88888888",
                ["description"] = "不可与其他优惠同享",
                ["date_info"] = new Dictionary<string, object>() { ["type"] = "DATE_TYPE_PERMANENT" },
                ["sku"] = new Dictionary<string, object>() { ["quantity"] = 0 },
                ["get_limit"] = 1,
                ["use_custom_code"] = true,
                ["get_custom_code_mode"] = "GET_CUSTOM_CODE_MODE_DEPOSIT",
                ["can_give_friend"] = true,
                ["custom_url_name"] = "订房首页",
                ["custom_url"] = "http://wuyu.cqutlab.cn/wxPage/Index",
                ["custom_url_sub_title"] = "4个分店选择",
                ["promotion_url_name"] = "订房页面",
                ["promotion_url"] = "http://wuyu.cqutlab.cn/wxPage/MainView",
                ["need_push_on_view"] = false,
            };

            Dictionary<string, object> member_card = new Dictionary<string, object>()
            {
                ["supply_bonus"] = false,
                ["supply_balance"] = false,
                ["prerogative"] = "test_prerogative",
                ["auto_activate"] = true,
                ["base_info"] = base_info
            };

            Dictionary<string, object> card = new Dictionary<string, object>()
            {
                ["card_type"] = "MEMBER_CARD",
                
                ["member_card"]=member_card,
                
            };

            Dictionary<string, object> map = new Dictionary<string, object>()
            {
                ["card"] = card,
            };
            string jsonmap= JsonConvert.SerializeObject(map);
            byte[] PostData = Encoding.UTF8.GetBytes(jsonmap);
            string url_cread = "https://api.weixin.qq.com/card/create?access_token=" + System.Web.HttpContext.Current.Application["acc_Token"].ToString();
            var client = new WebClient();
            client.Encoding = Encoding.UTF8;
            client.Headers.Add("Content-Type", "application/json");
            byte[] ResponseData = client.UploadData(url_cread, "POST", PostData);
            string SrcString = Encoding.UTF8.GetString(ResponseData);

            JObject jo = (JObject)JsonConvert.DeserializeObject(SrcString);
            string errmsg = jo["errmsg"].ToString();
            string card_id = jo["card_id"].ToString();
            

            string url_code = "http://api.weixin.qq.com/card/code/deposit?access_token=" + System.Web.HttpContext.Current.Application["acc_Token"].ToString();

            Dictionary<string, object> codemap = new Dictionary<string, object>()
            {
                ["card_id"] = card_id,
                ["code"] = "001",
            };

            string PostData_code = JsonConvert.SerializeObject(codemap);
            PostData= Encoding.UTF8.GetBytes(PostData_code);
            ResponseData = client.UploadData(url_code, "POST", PostData);
            SrcString = Encoding.UTF8.GetString(ResponseData);

            return View("WxCard");
        }



        public ActionResult CardView()
        {




            return View("WxCard");
        }


        //public ActionResult JSAPI_

    }
}